/**
 * 实时移动管理器
 * 时间：2021年12月15日 16:22:16
 * 采用：mapbox-gl
 * 平滑：实时滤波   
 * 版本：1.0.0
 */

import * as turf from 'turf'

// 存储所有飞机的状态
interface PlaneState {
    id: string; // 飞机唯一标识
    path: number[][]; // 飞机的路径
    currentIndex: number; // 当前路径点索引
    layerId: string; // 飞机图层的ID
    planeId: string; // 飞机数据源的ID
    isInitialized: boolean; // 是否已初始化
    animationFrameId: number; // 动画帧ID
}

// 飞机图片
interface Image {
    id: string,
    url: string
}

const planes: Record<string, PlaneState> = {}; // 所有飞机的状态
let map: any = null; // 地图对象
const realTimeMobile = {
    // 添加飞机图源
    loadPlaneImage: function (map: any, imageList: Image[]) {
        map = map; // 加载飞机图片
        // 加载飞机图片
        imageList.forEach((item: Image) => {
            map.loadImage(item.url, (error: any, image: any) => {
                if (error) throw error;
                if (!map.hasImage(item.id)) {
                    map.addImage(item.id + "_iago", image);
                }
            });
        })
    },
    // 更新飞机位置
    updatePlanePosition: function (map: any, planeId: string, newPosition: any) {

        if (planes[planeId]) {
            planes[planeId].path.push(newPosition);
            // 平滑路径
            planes[planeId].path = realTimeMobile.applyLowPassFilter(planes[planeId].path);
            // // 简化路径
            // const simplifiedPath = realTimeMobile.simplifyPath(planes[planeId].path, 0.001);

            // // 更新路径
            // planes[planeId].path = simplifiedPath;
            // console.log(planes[planeId].path );
            
            return;
        }

        // 初始化飞机状态
        planes[planeId] = {
            id: planeId,
            path: [newPosition],
            currentIndex: 0,
            layerId: `plane-layer-${planeId}`,
            planeId: `plane-source-${planeId}`,
            isInitialized: false,
            animationFrameId: 0,
        };
        // 添加飞机数据源
        map.addSource(planes[planeId].planeId, {
            type: 'geojson',
            data: {
                type: 'FeatureCollection',
                features: [
                    {
                        type: 'Feature',
                        geometry: {
                            type: 'Point',
                            coordinates: newPosition,
                        },
                    },
                ],
            },
        });
        // 添加飞机图层
        map.addLayer({
            id: planes[planeId].layerId,
            type: 'symbol',
            source: planes[planeId].planeId,
            layout: {
                'icon-image': 'plane-icon',
                'icon-size': 0.5,
                'icon-rotate': 0, // 初始方向
            },
        });
        // 初始化飞机状态
        planes[planeId].isInitialized = true;
        // 启动飞机移动
        realTimeMobile.movePlane(planeId);
    },
    // 低通滤波器函数
    applyLowPassFilter: function (path: number[][]): number[][] {
        const smoothedPath: number[][] = [];
        const alpha = 0.1; // 控制平滑程度（0-1之间）
        let prevPoint = path[0];

        smoothedPath.push(prevPoint);

        for (let i = 1; i < path.length; i++) {
            const currentPoint = path[i];
            const smoothedLongitude = alpha * currentPoint[0] + (1 - alpha) * prevPoint[0];
            const smoothedLatitude = alpha * currentPoint[1] + (1 - alpha) * prevPoint[1];
            const smoothedPoint = [smoothedLongitude, smoothedLatitude];
            smoothedPath.push(smoothedPoint);
            prevPoint = smoothedPoint;
        }

        return smoothedPath;
    },
    // 简化路径的Douglas-Peucker算法
    simplifyPath: function (path: number[][], tolerance: number): number[][] {
        const geojson = turf.lineString(path);
        const simplified = turf.simplify(geojson, { tolerance: tolerance, highQuality: false });
        return simplified.geometry.coordinates;
    },
    // 平滑移动飞机
    movePlane: function (planeId: string): void {
        const plane = planes[planeId];
        if (!plane) return;

        const totalPoints = plane.path.length;
        let currentIndex = plane.currentIndex;

        function animate(): void {
            if (currentIndex < totalPoints - 1) {
                const startPoint = plane.path[currentIndex];
                const endPoint = plane.path[currentIndex + 1];

                // 计算方向角
                const bearing = turf.bearing(turf.point(startPoint), turf.point(endPoint));

                // 更新飞机位置和方向
                (map.getSource(plane.planeId) as mapboxgl.GeoJSONSource).setData({
                    type: 'FeatureCollection',
                    features: [
                        {
                            type: 'Feature',
                            geometry: {
                                type: 'Point',
                                coordinates: startPoint,
                            },
                        },
                    ],
                });

                map.setLayoutProperty(plane.layerId, plane.id + "_iago", bearing);

                // 移动到下一个点
                currentIndex++;
                plane.currentIndex = currentIndex;

                // 保存动画帧ID
                plane.animationFrameId = requestAnimationFrame(animate);
            }
        }

        // 启动动画
        animate();
    }
}


export { realTimeMobile };

